package bar.dark.lee.setting.sms;

import java.math.BigDecimal;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.insert.InsertOutActivity;

public class SMSDialogActivity extends Activity implements OnClickListener {
	
	public static final int REQUEST_CATEGORY = 0;
	
	private String address, name, date, money, memo, linkCardName, linkCardType;
	private int smsType;
	private DBSQLite dbSql;
	private ArrayList<String> categoryList;
	
	private View categoryView;
	private TextView categoryTextView;
	private EditText memoEditText;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	    setContentView(R.layout.sms_dialog4);
	    
	    dbSql = DBSQLite.getInstance(this);
	    
	    Intent intent = getIntent();
	    address =intent.getStringExtra("address");
	    name = intent.getStringExtra("name");
	    date = intent.getStringExtra("date");
	    money = intent.getStringExtra("money");
	    memo = intent.getStringExtra("memo");
	    linkCardName = intent.getStringExtra("linkCardName");
	    linkCardType = intent.getStringExtra("linkCardType");
	    smsType = intent.getIntExtra("smsType", BDConstents.OUT_SMS);
	    
	    categoryView = findViewById(R.id.smsDialog4_textResultView6);
	    categoryTextView = ((TextView)findViewById(R.id.smsDialog4_textResult6));
	    memoEditText = ((EditText)findViewById(R.id.smsDialog4_textResult5));
	    
	    getCategoryList();
	    
	    if (smsType == BDConstents.IN_SMS || smsType == BDConstents.IN_ATM_SMS)
	    {
	    	((TextView)findViewById(R.id.smsDialog4_textTitle)).setText("입금 문자가 도착했습니다.");
	    	((TextView)findViewById(R.id.smsDialog4_textResultTitle3)).setText("입금날짜  :  ");
		    ((TextView)findViewById(R.id.smsDialog4_textResultTitle4)).setText("입금금액  :  ");
		    ((TextView)findViewById(R.id.smsDialog4_textResultTitle5)).setText("입금내역  :  ");
	    }
	    else if (smsType == BDConstents.OUT_ATM_SMS)
	    {
	    	((TextView)findViewById(R.id.smsDialog4_textTitle)).setText("출금 문자가 도착했습니다.");
	    	((TextView)findViewById(R.id.smsDialog4_textResultTitle3)).setText("출금날짜  :  ");
		    ((TextView)findViewById(R.id.smsDialog4_textResultTitle4)).setText("출금금액  :  ");
		    ((TextView)findViewById(R.id.smsDialog4_textResultTitle5)).setText("출금내역  :  ");
	    }
	    
	    ((TextView)findViewById(R.id.smsDialog4_textResult1)).setText(address);
	    ((TextView)findViewById(R.id.smsDialog4_textResult2)).setText(name);
	    ((TextView)findViewById(R.id.smsDialog4_textResult3)).setText(date);
	    ((TextView)findViewById(R.id.smsDialog4_textResult4)).setText(money);
	    ((EditText)findViewById(R.id.smsDialog4_textResult5)).setText(memo);
	    
	    findViewById(R.id.smsDialog4_textResult6).setOnClickListener(this);
	    findViewById(R.id.smsDialog4_btnConfirm).setOnClickListener(this);
	    findViewById(R.id.smsDialog4_btnCancel).setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) 
		{
			case R.id.smsDialog4_textResult6:
				Intent intent = new Intent(this, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, categoryList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryTextView.getText().toString());
				
				if (smsType == BDConstents.IN_SMS || smsType == BDConstents.IN_ATM_SMS)
				{
					intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_IN_TYPE);
					intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_IN_TYPE_STRING);
				}
				else
				{
					intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_OUT_TYPE);
					intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_OUT_TYPE_STRING);
				}
				
				startActivityForResult(intent, REQUEST_CATEGORY);
			break;
			case R.id.smsDialog4_btnConfirm:
				SMSInsertDB insertDB = new SMSInsertDB();
				
				BigDecimal tempMoney = new BigDecimal(money);
				
				// 신용카드
				if (linkCardType.equalsIgnoreCase("3")) 
				{
					try
					{
						dbSql.beginTansaction(this);
						
						insertDB.creditOutInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
						
						// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
						if (linkCardType.equals("") || linkCardName.equals(""))
						{
							throw new Exception();
						}
						
						// 잔액을 입력한다.
						BalanceQuery balace = new BalanceQuery(this);
						balace.setBalance(BDConstents.CREDIT_TYPE, linkCardName);
						
						dbSql.setTransactionSuccessful();
					} catch (Exception e)
					{
						//Toast.makeText(this, "꿀꿀이 가계부 입력 실패! 개발자에게 문의하세요!", Toast.LENGTH_SHORT).show();
					} finally {
						try 
						{
							dbSql.endTransaction(this);
						} catch (Exception e) 
						{
						}
					}
				} 
				// 체크카드
				else if (linkCardType.equalsIgnoreCase("4")) 
				{
					try
					{
						dbSql.beginTansaction(this);
						
						// 지출, 수입 플래그
						int flag = 0;
						
						if (smsType == BDConstents.IN_SMS)
						{
							insertDB.checkInInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_SMS)
						{
							insertDB.checkOutInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 0;
						}
						else if (smsType == BDConstents.IN_ATM_SMS)
						{
							insertDB.checkInAtmInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_ATM_SMS)
						{
							insertDB.checkOutAtmInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 0;
						}
						
						// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
						if (linkCardType.equals("") || linkCardName.equals(""))
						{
							throw new Exception();
						}
						
						// 잔액을 입력한다.
						BalanceQuery balace = new BalanceQuery(this);
						balace.setBalance(BDConstents.CHECK_TYPE, linkCardName);
						
						dbSql.setTransactionSuccessful();
					} catch (Exception e)
					{
						//Toast.makeText(this, "꿀꿀이 가계부 입력 실패! 개발자에게 문의하세요!", Toast.LENGTH_SHORT).show();
					} finally {
						try 
						{
							dbSql.endTransaction(this);
						} catch (Exception e) 
						{
						}
					}
				}
				// 통장
				else if (linkCardType.equalsIgnoreCase("1")) 
				{
					try
					{
						dbSql.beginTansaction(this);
						
						// 지출, 수입 플래그
						int flag = 0;
						
						if (smsType == BDConstents.IN_SMS)
						{
							insertDB.bankInInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_SMS)
						{
							insertDB.bankOutInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 0;
						}
						else if (smsType == BDConstents.IN_ATM_SMS)
						{
							insertDB.bankInAtmInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_ATM_SMS)
						{
							insertDB.bankOutAtmInsert(this, dbSql, linkCardType, linkCardName, date, tempMoney, memoEditText.getText().toString().trim(), categoryTextView.getText().toString());
							flag = 0;
						}
						
						// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
						if (linkCardType.equals("") || linkCardName.equals(""))
						{
							throw new Exception();
						}
						
						// 잔액을 입력한다.
						BalanceQuery balace = new BalanceQuery(this);
						balace.setBalance(BDConstents.BANK_TYPE, linkCardName);
						
						dbSql.setTransactionSuccessful();
					} catch (Exception e)
					{
						//Toast.makeText(this, "꿀꿀이 가계부 입력 실패! 개발자에게 문의하세요!", Toast.LENGTH_SHORT).show();
					} finally {
						try 
						{
							dbSql.endTransaction(this);
						} catch (Exception e) 
						{
						}
					}
				}
				//BDUtil.showToast(this, "가계부에 내역을 입력했습니다");
				finish();
			break;
			case R.id.smsDialog4_btnCancel:
				finish();
			break;
			default:
			break;
		}
	}
	
	private void getCategoryList()
	{
		String query = "";
		if (smsType == BDConstents.IN_SMS || smsType == BDConstents.IN_ATM_SMS)
		{
			query = "SELECT kind FROM category_in_list ORDER BY count DESC";
		}
		else
		{
			query = "SELECT kind FROM category_out_list ORDER BY count DESC";
		}
		dbSql.selectMapTile(this, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				categoryList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("kind");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					categoryList.add(kind);
					c.moveToNext();
				}
				
				if (categoryList.size() < 1)
				{
					String memo = "없음";
					categoryList.add(memo);
					categoryView.setClickable(false);
				}
				
				categoryTextView.setText(categoryList.get(0).toString());
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_CATEGORY)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				categoryTextView.setText(selectData);
			}
			else if (resultCode == RadioDialogActivity.REFRESH_CATEGORY)
			{
				final String beforeCategory = categoryTextView.getText().toString();
				
				String query = "";
				if (smsType == BDConstents.IN_SMS || smsType == BDConstents.IN_ATM_SMS)
				{
					query = "SELECT kind FROM category_in_list ORDER BY count DESC";
				}
				else
				{
					query = "SELECT kind FROM category_out_list ORDER BY count DESC";
				}
				
				dbSql.selectMapTile(this, query, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						categoryList = new ArrayList<String>();
						
						int nameIndex = c.getColumnIndex("kind");
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							String kind = c.getString(nameIndex);
							categoryList.add(kind);
							c.moveToNext();
						}
						
						if (categoryList.size() < 1)
						{
							String memo = "없음";
							categoryList.add(memo);
							categoryView.setClickable(false);
						}
						
						categoryTextView.setText(beforeCategory);
					}
				});
			}
		}
	}
}
